<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="showCateDialogVisible">添加分类</el-button>
      <!-- 分类名称栏 -->
      <tree-table
        :data="catesList"
        :columns="columns"
        :show-row-hover="false"
        border
        :expand-type="false"
        :selection-type="false"
        show-index
        index-text="#"
        class="TreeTable"
      >
        <!-- 是否有效栏 -->
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted===false" style="color:lightgreen;"></i>
          <i class="el-icon-error" v-else style="color:red;"></i>
        </template>
        <!-- 排序栏 -->
        <template slot="sort" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level ==0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level ==1">二级</el-tag>
          <el-tag type="warning" v-else-if="scope.row.cat_level ==2">三级</el-tag>
        </template>
        <!-- 操作栏 -->
        <template slot="operate" width="300px" slot-scope="scope">
          <!-- 编辑功能@click="showEditDialog(scope.row.id)" -->
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditDialog(scope.row.cat_id)"
          >编辑</el-button>
          <!-- 删除功能 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeRole(scope.row.cat_id)"
          >删除</el-button>
        </template>
      </tree-table>
      <!-- 分页布局 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 添加分类对话框 -->
      <el-dialog
        title="添加分类"
        :visible.sync="cateDialogVisible"
        width="50%"
        @close="addCateDialogClosed"
      >
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
          <!-- label-width是左边的文本宽度 -->
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <!-- 父级分类文本框 
              options 用来指定数据源
              props 用来指定配置对象
              v-model绑定的必须是一个数组，不能是一个具体的值
            @change="parentCateChanged"：当级联选择器点击所选项后触发-->
            <el-cascader
              expand-trigger="hover"
              v-model="selectedKeys"
              :options="parentCateList"
              :props="cascaderProps"
              @change="parentCateChanged"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑分类对话框 -->
      <el-dialog title="修改分类" :visible.sync="editDialogVisible" width="50%">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="editForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCate">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      queryInfo: {
        //三层列表数据
        type: 3,
        //当前页数
        pagenum: 1,
        //当前页显示的条数
        pagesize: 5
      },
      total: 0,
      //存储商品分类的数据
      catesList: [],
      //存储父级分类数据
      parentCateList: [],
      //级联选择器的配置属性，checkStrictly设置为true后可以只选择一级分类
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true
      },
      //级联选择器选中的数据
      selectedKeys: [],
      //存储添加分类的对话框中的双向绑定数据
      addForm: {
        //分类父 ID
        cat_pid: 0,
        //分类名称
        cat_name: '',
        //分类层级，默认要添加的是一个一级的分类
        cat_level: 0
      },
      //存储编辑分类的对话框中的双向绑定数据
      editForm: {},
      //存储每其他列的数据
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
          width: '400px'
        },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          type: 'template',
          template: 'isok'
        },
        {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          template: 'sort'
        },
        {
          label: '操作',
          type: 'template',
          template: 'operate',
          width: '180px'
        }
      ],
      //设置添加分类对话框的显示与隐藏
      cateDialogVisible: false,
      //设置编辑分类对话框的显示与隐藏
      editDialogVisible: false,
      //设置删除分类对话框的显示与隐藏
      removeDialogVisible: false,
      //存储添加分类对话框的表单验证数据
      addFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      //存储编辑分类对话框的表单验证数据
      editFormRules: {
        cat_name: [
          {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getCatesList()
  },
  methods: {
    //获取分类列表数据
    async getCatesList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200)
        return this.$message.error('获取商品分类数据失败！')
      this.catesList = res.data.result
      this.total = res.data.total
    },
    //改变每页条数
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCatesList()
    },
    //改变当前页
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCatesList()
    },
    //弹出添加分类对话框时，获取父级分类数据
    showCateDialogVisible() {
      this.getParentCateList()
      this.cateDialogVisible = true
    },
    //获取父级分类数据
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: 2
        }
      })
      if (res.meta.status !== 200)
        return this.$message.error('获取父级分类失败！')
      this.parentCateList = res.data
      // console.log(this.parentCateList);
    },
    //当级联选择器的值发生变化时触发
    parentCateChanged() {
      //如果没选
      if (this.selectedKeys.length > 0) {
        this.addForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        this.addForm.cat_level = this.selectedKeys.length
        return
      } else {
        this.addForm.cat_pid = 0
        this.addForm.cat_level = 0
      }
    },
    //点击添加分类的对话框“确定”按钮
    addCate() {
      //进行预校验，并post上传数据
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('categories', this.addForm)
        if (res.meta.status !== 201)
          return this.$message.error('添加分类失败！')
        this.$message.success('添加分类成功')
        this.getCatesList()
        this.cateDialogVisible = false
      })
    },
    //当添加分类对话框消失时触发
    addCateDialogClosed() {
      this.$refs.addFormRef.resetFields()
      this.addForm.cat_pid = 0
      this.addForm.cat_level = 0
      this.selectedKeys = []
    },
    //点击“编辑”按钮，触发该事件，显示编辑对话框，并根据传过来的id获取对应行的数据
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(`categories/${id}`)
      if (res.meta.status !== 200) return this.$message.error('查询分类失败！')
      this.editForm = res.data
      // console.log(this.editForm);
    },
    //编辑分类
    editCate() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.editForm.cat_id}`,
          {
            cat_name: this.editForm.cat_name
          }
        )
        if (res.meta.status !== 200)
          return this.$message.error('修改分类失败！')
        this.editDialogVisible = false
        this.getCatesList()
        this.$message.success('修改分类成功！')
      })
    },
    //删除分类
    async removeRole(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该分类, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(confirmResult);
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除！')
      const { data: res } = await this.$http.delete('categories/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除分类失败！')
      this.$message.success('删除分类成功！')
      this.getCatesList()
    }
  }
}
</script>
<style lang="less" scoped>
.TreeTable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>


